import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_main_tabbar.dart';
import 'package:flutter_code_framework/model_data/lessonreview/lessonreview.dart';
import 'package:flutter_code_framework/route/route_transition.dart';

import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_code_framework/base/base_widget.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

// ignore: must_be_immutable
class LessonReview extends BaseWidget {
  String preLessonId;
  LessonReview({Key key, this.preLessonId}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _LessonReviewState();
  }
}

class _LessonReviewState extends BaseWidgetState<LessonReview> {
  ScrollController _controller = ScrollController();
  List<Object> listData = [];
  var idx = 0;
  bool isLoadFinish = false;
  @override
  Widget buildWidget(BuildContext context) {
    return Column(
      children: <Widget>[
        SizedBox(height: 7),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(SFSymbols.tray_arrow_down_fill,
                size: 14, color: G.ADColor("#EC7364")),
            SizedBox(width: 5),
            GestureDetector(
              child: Text(
                "查看课程信息",
                style: TextStyle(
                    fontSize: 14.0,
                    color: Theme.of(context).primaryTextTheme.caption.color),
              ),
              onTap: () => _scanLesson(),
            ),
          ],
        ),
        SizedBox(height: 6),
        Expanded(
          child: Container(
            height: double.maxFinite,
            child: isLoadFinish ? getListView(context) : Container(),
          ),
        ),
        // SizedBox(height: kTabbarHeigt),
      ],
    );
  }

  _scanLesson() {
    //RouteTransition(BaseMainTabbarPage()).pushAndRemoveUntilTransRoute(context);
    Navigator.of(context).pop();
  }

  ///子类获取Listview ，重写相关方法自定义数据和布局。
  @override
  Widget getListView(BuildContext context) {
    Widget mainWidget;
    //默认空数据状态
    if (listData == null ||
        listData.length == 0 ||
        (listData.length == 1 && listData[0] == null)) {
      mainWidget = getEmptyWidget();
    } else {
      // RefreshIndicator为ListView增加了下拉刷新能力，onRefresh参数传入一个方法，在下拉刷新时调用
      mainWidget = ListView.builder(
        shrinkWrap: true,
        //physics: NeverScrollableScrollPhysics(),
        //physics: BouncingScrollPhysics(),
        scrollDirection: Axis.vertical,
        itemCount: listData.length,
        itemBuilder: (context, index) {
          return _renderRow(index);
        },
        controller: _controller,
        physics: AlwaysScrollableScrollPhysics(),
      );
    }
    return mainWidget;
  }

  //初始化项目结构
  Widget _renderRow(int index) {
    Widget itemWidget;
    itemWidget = Row(
      children: <Widget>[
        Expanded(
          child: getItemWidet(index),
        ),
      ],
    );

    return InkWell(
      child: Padding(
        padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
        child: itemWidget,
      ),
      onTap: () {
        listViewItemFunction(index);
        //需独立context
        Slidable.of(context)?.renderingMode == SlidableRenderingMode.none
            ? Slidable.of(context)?.open()
            : Slidable.of(context)?.close();
      },
    );
  }

  @override
  Widget getItemWidet(int index) {
    ClassInfo model = listData[index];
    if (model == null) {
      return Container();
    }
    // List<Widget> listUser = [];
    // Widget w = Container();
    // for (var item in model.userInfo) {
    //   listUser
    //       .add(Icon(SFSymbols.bookmark_fill, size: 16.0, color: Colors.green));
    // }
    var thisColor = model.joinCnt > 0
        ? G.ADColor("#39876E")
        : Theme.of(context).primaryTextTheme.caption.color;
    return Column(
      children: <Widget>[
        GestureDetector(
          child: Container(
            height: 72.0,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(height: 10),
                Row(
                  children: <Widget>[
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        "${model.className.length > 12 ? model.className.substring(0, 12) + "..." : model.className}",
                        style: TextStyle(
                            color: Theme.of(context)
                                .primaryTextTheme
                                .caption
                                .color,
                            fontSize: 18.0),
                      ),
                    )
                  ],
                ),
                SizedBox(height: 7),
                Row(
                  children: <Widget>[
                    Text(
                      "参与者${model.joinCnt.toString()}人",
                      style: TextStyle(color: thisColor, fontSize: 14.0),
                    ),
                    SizedBox(width: 2),
                    Text('|',
                        style: TextStyle(
                            color:
                                Theme.of(context).primaryTextTheme.caption.color
                            //Color.fromRGBO(118,118,118,1)
                            ,
                            fontSize: 14.0)),
                    SizedBox(width: 2),
                    Text(
                      "未参与者${model.unJoinCnt.toString()}人",
                      style: TextStyle(
                          color:
                              Theme.of(context).primaryTextTheme.caption.color,
                          fontSize: 14.0),
                    ),
                    SizedBox(width: 2),
                    Text('|',
                        style: TextStyle(
                            color:
                                Theme.of(context).primaryTextTheme.caption.color
                            //Color.fromRGBO(118,118,118,1)
                            ,
                            fontSize: 14.0)),
                    SizedBox(width: 2),
                    Text(
                      "参与率${model.joinRate}",
                      style: TextStyle(
                          color:
                              Theme.of(context).primaryTextTheme.caption.color,
                          fontSize: 14.0),
                    ),
                  ],
                ),
                SizedBox(height: 6.0),
                Divider(
                    height: 1,
                    color: Theme.of(context).primaryTextTheme.caption.color),
              ],
            ),
          ),
          onTap: () {
            setState(() {
              idx = index;
              print("idx:" + idx.toString());
            });
          },
        ),
        SizedBox(height: 5.0),
        Offstage(
          offstage: index != idx,
          child: Container(
              //height: MediaQuery.of(context).size.height,
              alignment: Alignment.topLeft,
              // constraints: BoxConstraints(
              //   maxHeight: 240.0,
              //   minHeight: 0.0,
              // ),
              child: SingleChildScrollView(
                //physics: BouncingScrollPhysics(),
                child: Wrap(
                  alignment: WrapAlignment.start,
                  children: <Widget>[
                    // ignore: sdk_version_ui_as_code
                    for (var one in model.userInfo) _userInfo(one)
                  ],
                ),
              )),
        ),
      ],
    );
  }

  Widget _userInfo(UserInfo model) {
    IconData icon;
    Color iconColor;
    if (model.flag == "1") {
      icon = SFSymbols.bookmark_fill;
      iconColor = G.ADColor("#39876E");
    } else {
      icon = SFSymbols.bookmark;
      iconColor = Theme.of(context).primaryTextTheme.caption.color;
    }

    return Container(
      padding: EdgeInsets.fromLTRB(6, 12, 6, 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Icon(icon, size: 12.0, color: iconColor),
          Text(
            model.userName,
            style: TextStyle(fontSize: 12.0, color: iconColor),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    try {
      var maxScroll = _controller.position.maxScrollExtent;
      var pixels = _controller.position.pixels;
      print('maxscroll = ' +
          maxScroll.toString() +
          'current pix = ' +
          pixels.toString());
    } catch (e) {}
    initReviewData(widget.preLessonId);
    _controller.addListener(() {});
  }

  ///初始化数据
  Future<Null> initReviewData(String preLessonId) async {
    // 模拟等待3秒钟[]
    // await Future.delayed(Duration(seconds: 3), () {
    //   //初始数据

    // });
    getData(preLessonId);
  }

  getData(String preLessonId) async {
    var response = await G.req.lessonData.getReviewList(preLessonId);
    print("response:" + response.toString());
    if (mounted) {
      setState(() {
        isLoadFinish = true;
        listData.addAll(response.data["classInfo"]
            .map((e) => ClassInfo.fromJson(e))
            .toList());
      });
    }
  }

  // @override
  // Widget getTopNavRightWidget(BuildContext _contextBaseFunction) {
  //   return Container(
  //     //图标+查看课程信息 总宽100；父padright24
  //     padding: EdgeInsets.only(right: getScreenWidth() / 2 - 24 - 50),
  //     child: Row(
  //       mainAxisAlignment: MainAxisAlignment.start,
  //       children: <Widget>[
  //         Icon(SFSymbols.tray_arrow_up_fill,
  //             size: 14, color: G.ADColor("#EC7364")),
  //         SizedBox(width: 5),
  //         GestureDetector(
  //           child: Text(
  //             "查看课程信息",
  //             style: TextStyle(
  //                 fontSize: 14.0,
  //                 color: Theme.of(context).primaryTextTheme.caption.color),
  //           ),
  //           onTap: () => _scanLesson(),
  //         ),
  //       ],
  //     ),
  //   );
  // }

  @override
  void onCreate() {
    //setAppTopNavBarVisible(true);
    //setTopNavLeftIcon(SFSymbols.xmark);
  }

  @override
  void onPause() {}

  @override
  void onResume() {}
}
